//
//  photoCell.m
//  项目一TimeMovie
//
//  Created by apple on 16/4/7.
//  Copyright © 2016年 huangmingyu. All rights reserved.
//

#import "photoCell.h"
#import "UIView+viewController.h"

@implementation photoCell {
    
    UIImageView *imgView;
    UIAlertController *alertCtrl;
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        [self createImageView];
    }
    return self;
}

- (void)awakeFromNib {
    
    [super awakeFromNib];
    [self createImageView];
}

- (void)setImgUrlStr:(NSString *)imgUrlStr {
    
    
    _imgUrlStr = imgUrlStr;
    [imgView sd_setImageWithURL:[NSURL URLWithString:_imgUrlStr]];
}

- (void)createImageView {
    
    imgView = [[UIImageView alloc] initWithFrame:self.bounds];
    
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    
    imgView.userInteractionEnabled = YES;
    
    [imgView addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(savePhoto:)]];
    
    [self.contentView addSubview:imgView];
}

- (void)savePhoto:(UIGestureRecognizer *)longPress {
    
//    if (longPress.state == UIGestureRecognizerStateBegan) {
    
        
    
        alertCtrl = [UIAlertController alertControllerWithTitle:@"是否保存图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [alertCtrl addAction:[UIAlertAction actionWithTitle:@"123" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            MBProgressHUD  *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];

            
            UIImage *img = imgView.image;
            hud.labelText = @"存储中";
            hud.dimBackground = YES;
            if (img != nil) {
                
                UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void * _Nullable)(hud));
            }
        }]];
       
        
        [alertCtrl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL]];
        
        [self.viewController presentViewController:alertCtrl animated:YES completion:NULL];

//    }
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    MBProgressHUD *hud = (__bridge MBProgressHUD *)(contextInfo);
    
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark"]];
    hud.mode = MBProgressHUDModeCustomView;
    hud.labelText = @"保存成功";
    
    [hud hide:YES afterDelay:2];
    NSLog(@"保存成功!");
    
    [alertCtrl dismissViewControllerAnimated:YES completion:NULL];
}

@end
